<?php
namespace api\service;

use api\service\interfaces\IUserService;
use api\utils\SaasApiClient;
use herosphp\bean\Beans;
use herosphp\core\Loader;
use herosphp\string\StringUtils;
use herosphp\utils\AjaxResult;

Loader::import('api.service.interfaces.IUserService');

/**
 * user api(Service)接口实现
 * @author Liuyi<liuy@pvc123.com>
 */
class UserService implements IUserService {


    /**
     * 注册大塑支付服务
     * @param $data array
     * @return mixed
     */
    public function register($data)
    {
        $userService = Beans::get('user.user.service');
        //验证用户名
        if ( $userService->count(array('username' => $data['username'])) > 0 ) {
            return AjaxResult::fail('账号已经存在,请直接绑定即可！');
        }
        $data['id'] = StringUtils::genGlobalUid(false, 24);
        if ( $userService->add($data) != false ) {
            $result = new AjaxResult(AjaxResult::OP_SUCCESS, "register successfully", null);
            $result -> putItem($data['id']);
            return $result;
        } else {
            return new AjaxResult(AjaxResult::OP_FAILURE, "register fail", null);
        }
    }

    /**
     * @see IUserService::registerCompany
     */
    public function registerCompany($user, $company) {
        $userService = Beans::get('user.user.service');
        $companyService = Beans::get('user.company.service');
        //验证用户名
        if ( $userService->count(array('username' => $user['username'])) > 0 ) {
            return AjaxResult::fail('账号已经存在,请直接绑定即可！');
        }
        $user['id'] = StringUtils::genGlobalUid(false, 24);
        $user['addtime'] = date('Y-m-d H:i:s');
        $user['updatetime'] = date('Y-m-d H:i:s');
        $user['type'] = 2;

        $userService->beginTransaction(); //开始事务
        if ( $userService->add($user) ) {
            $company['userid'] = $user['id'];
            $company['addtime'] = $user['addtime'];
            $company['updatetime'] = $user['addtime'];
            $company['register_capital'] = floatval($company['register_capital']);
            if ( $companyService->add($company) ) {
                $userService->commit();
                return AjaxResult::success("注册成功", array(AjaxResult::DATA_KEY_ITEM, $user));
            } else {
                $userService->rollback();
            }

        }
        return AjaxResult::fail("注册失败");
    }

    /**
     * 校验手机号是否已经注册
     * @author LiuYi
     * @param $mobile
     * @return AjaxResult
     */
    public function checkUser($mobile){
        $userService = Beans::get('user.user.service');
        //验证用户名
        if ( $userService->count(array('username' => $mobile)) > 0 ) {
            return new AjaxResult(AjaxResult::OP_FAILURE, "账号已经存在,请直接绑定即可！", null);
        }else{
            return new AjaxResult(AjaxResult::OP_SUCCESS, "可以注册", null);
        }
    }

    /**
     * MPE系统终端用户绑定大塑支付 接口
     * @see \api\service\interfaces\IUserService::bind
     */
    public function bind($username, $password, $app_username, $app_userid)
    {
        if ( func_num_args() < 4 ) return AjaxResult::fail("缺少必填参数.");

        $password = md5($password);
        $userService = Beans::get('user.user.service');
        $item = $userService->getItem(array('username' => $username,'password'=>$password), array('id','username','virtual_name','contacter','sign_status','ischecked'));
        if( $item ){
            $resVo = AjaxResult::success('绑定成功');
            $resVo->putItem($item);

            //添加绑定记录
            $bindLogModel = Loader::model('UserBindLog');
            $mpeVo = SaasApiClient::send('api/mpe/getItem', array('mpeid' => getAPPID()));
            $mpe = $mpeVo->getItem();
            $__data['appid'] = getAPPID();
            $__data['company'] = $mpe['company'];
            $__data['username'] = $username;
            $__data['userid'] = $item['id'];
            $__data['app_username'] = $app_username;
            $__data['app_userid'] = $app_userid;
            $__data['addtime'] = date('Y-m-d H:i:s');
            $bindLogModel->add($__data);

            return $resVo;
        }
        return new AjaxResult(AjaxResult::OP_FAILURE,"error password or username",null);
    }

    /**
     * @see \api\service\interfaces\IUserService::bindApp
     */
    public function bindApp($username)
    {
        $userService = Beans::get('user.user.service');
        $user  = $userService->getItem(array('username' => $username));

        if ( $user == false ) return AjaxResult::fail('绑定失败, 用户不存在.');
        if ( $user['ischecked'] != 2 ) return AjaxResult::fail('绑定失败, 用户未实名认证.');
        if ( $user['sign_status'] != 1 ) return AjaxResult::fail('绑定失败, 用户未签约.');
        if ( $user['type'] != 2 ) return AjaxResult::fail('绑定失败，该用户非企业用户.');

        $resVo =  AjaxResult::success('绑定成功.');
        $resVo->putItem(array('userid' => $user['id'], 'username' => $user['username'], 'company' => $user['company']['company']));
        return $resVo;
    }

    /**
     * MPE个人中心 -- 账号安全调用
     * @author LiuYi
     * @param   $userid int MPE用户绑定的大塑支付ID
     * @param   $fields String 需要返回的字段
     * @return AjaxResult
     */
    public function getUserInfo($userid, $fields = "*")
    {
        if( !$userid ){
            return new AjaxResult(AjaxResult::OP_FAILURE,"error params",null);
        }
        //获取用户基本信息
        $userService = Beans::get('user.user.service');
        $res = $userService ->getItem(array('id' => $userid),$fields,null);
        if( $res ){
            $resVo = new AjaxResult(AjaxResult::OP_SUCCESS,"success",null);
            if( $res['ischecked'] == 2 ){

                $companyService = Beans::get('user.company.service');
                $company = $companyService -> getItem(array('userid'=>$userid),"company,idcard_no",null);
                $res['company']=$company['company'];
                $res['idcard_no']=$company['idcard_no'];
            }
            if( $res['sign_status'] == 1) {

                //加载签约银行的中文名称
                $bankService = Beans::get('payment.bank.service');
                $bank_id = $res['sign_bank_id'];
                $bankItem = $bankService -> getItem(array('id' => $bank_id), "id,name",null);
                if ($bankItem === false) {
                    return new AjaxResult(AjaxResult::OP_FAILURE,"Bank not found",null);
                }
                $res['bank_name'] = $bankItem['name'];
                //去加载支付通道的中文名称
                $pay_id = $res['payway'];
                $payService = Beans::get('payment.payway.service');
                $payItem = $payService->getItem(array('id' => $pay_id), "id,name", null);
                if ($payItem !== false) {
                    $res['payName'] = $payItem['name'];
                    $resVo -> putItem($res);
                    return $resVo;
                }else{
                    return new AjaxResult(AjaxResult::OP_FAILURE,"payWay not found",null);
                }
            }else{
                $resVo -> putItem($res);
                return $resVo;
            }
        }else {
            return new AjaxResult(AjaxResult::OP_FAILURE, "dasu_pay_id not found", null);
        }
    }

    /**
     * 根据传入的大塑支付id数组，返回大塑支付账号相关信息，此方法是查询多条数据时使用，查询一条的可以使用getUserInfo()
     * @param array $conditions=array('id'=>array('$in' => array(1,2,3...)))
     * @param string $fields="id,total_cost,name..."
     * @return AjaxResult
     */
    public function getUsersInfo( $conditions, $fields="*", $order, $page=0, $pagesize=2147483648){
        if( empty($conditions) ){
            return new AjaxResult(AjaxResult::OP_FAILURE,"error params",null);
        }
        $userService = Beans::get('user.user.service');
        $res = $userService ->getItems($conditions,$fields,$order,$page.','.$pagesize,null,null);
        if( $res ) {
            $resVo = new AjaxResult(AjaxResult::OP_SUCCESS, "success", null);
            $resVo -> putItems($res);
            return $resVo;
        } else {
            return new AjaxResult(AjaxResult::OP_SUCCESS,"Nothing be Found",null);
        }
    }

    /**
     * MPE会员获取资质审核状态
     * @param $userid int Mpe会员绑定的大塑支付ID
     * @return AjaxResult
     */
    public function getUserCheckStatus( $userid ) {

        $service = Beans::get('user.company.service');
        $item = $service -> getItem(array('userid'=>$userid),"id,ischecked",null);
        if( $item !==false ){
            if( empty($item)){
                return new AjaxResult(AjaxResult::OP_SUCCESS,"check status not know",null);
            } else {
                $resVo = new AjaxResult(AjaxResult::OP_SUCCESS,"success",null);
                $resVo -> putItem($item);
                return $resVo;
            }
        }else{
            return new AjaxResult(AjaxResult::OP_FAILURE,"database error",null);
        }
    }

    /**
     * MPE通过实名认证查询大塑支付会员ID
     * @param $name
     * @return AjaxResult
     */
    public function getIdByName($name){
        $conditions['name'] = "%".$name."%";
        $service = Beans::get('user.user.service');
        $items = $service -> getItems($conditions,"id,ischecked");
        if( $items ){
            $resVo = new AjaxResult(AjaxResult::OP_SUCCESS,"success",null);
            $resVo -> putItems($items);
            return $resVo;
        }else{
            return new AjaxResult(AjaxResult::OP_SUCCESS,"null",null);
        }
    }

    /**
     * MPE 银行签约接口
     * @param $userid  int MPE用户绑定的大塑支付ID
     * @param $signData array 银行相关信息
     * @return AjaxResult
     */
    public function signBank($userid,$signData){

        $service = Beans::get('user.user.service');
        if ( $service->signBank($userid, $signData) ) {
            $resVo = new AjaxResult(AjaxResult::OP_SUCCESS,"sign success!",null);
            return $resVo;
        } else {
            return new AjaxResult(AjaxResult::OP_FAILURE,"sign fail!",null);
        }

    }

    /**
     * MPE 银行解约接口
     * @param $userid
     * @return AjaxResult
     */
    public function unSignBank($userid) {
        //如果该用户的附属账户还有余额，则不允许解约
        $paymentService = Beans::get('api.payment.service');
        $res = $paymentService->getBalance($userid);
        if ( $res->isSucess() ) {
            $data = $res->getData();
            if ( $data['balance'] > 0 ) {
                return  new AjaxResult(AjaxResult::OP_FAILURE, LANG('VIR_ACCOUNT_NOT_CLEAR'),null);
            }
        } else {
            return new AjaxResult(AjaxResult::OP_FAILURE, LANG('QUERY_BALANCE_FAILD'),null);
        }
        $service = Beans::get('user.user.service');
        if ( $service->unsignBank($userid) ) {
            return new AjaxResult(AjaxResult::OP_SUCCESS, "解约成功",null);
        } else {
            return new AjaxResult(AjaxResult::OP_FAILURE, "解约失败",null);
        }
    }

    /**
     * MPE用户提交的资质审核,如果是重复认证的就更新数据，否则插入新的数据
     * @param $companyData array MPE用户提交的企业信息和认证信息,必需包含$userid
     * @return AjaxResult
     */
    public function userAuth($companyData){
        if( !is_array($companyData) ){
            return new AjaxResult(AjaxResult::OP_FAILURE,"error params",null);
        }
        $companyService = Beans::get('user.company.service');
        if( !$companyData['userid'] || empty($companyData)){
            return new AjaxResult(AjaxResult::OP_FAILURE,"error params!",null);
        }
        if($companyService ->replace($companyData) !==false){
            $userService = Beans::get('user.user.service');
            $userService -> set('ischecked',1,$companyData['userid']);
            return new AjaxResult(AjaxResult::OP_SUCCESS,"update success",null);
        } else{
            return new AjaxResult(AjaxResult::OP_FAILURE,"update failure!",null);
        }
    }

    /**
     * MPE 设置/修改交易密码接口
     * @param $userid int 绑定的大塑支付id
     * @param $password String Md5之后的密码
     * @return AjaxResult
     */
    public function tradePass( $userid, $password ){
        if ( !$userid || !$password ) {
            return new AjaxResult(AjaxResult::OP_FAILURE,"error params",null);
        }
        $service = Beans::get('user.user.service');
        if( $service -> set('tradepass',$password,$userid) ){
            return new AjaxResult(AjaxResult::OP_SUCCESS,"success",null);
        }else{
            return new AjaxResult(AjaxResult::OP_FAILURE,"update failure",null);
        }
    }

    /**
     * 获取认证用户的企业资质信息
     * @param $userid  int MPE用户绑定的大塑支付ID
     * @param $fields  String  需要获取的字段
     * @return AjaxResult
     */
    public function getCompanyInfo( $userid, $fields="*" ){
        if( !$userid ){
            return new AjaxResult(AjaxResult::OP_FAILURE,"error params",null);
        }
        $service = Beans::get('user.company.service');
        $item = $service -> getItem(array('userid'=>$userid),$fields,null);
        if( $item ){

            /*
            if( strpos($fields,'*') !==false || (strpos($fields,'prov') !==false && strpos($fields,'prov') !==false && strpos($fields,'prov')) !==false ) {
                //拼接地址信息
                $item['provName'] = getAreaName($item['prov']);
                $item['cityName'] = getAreaName($item['city']);
                $item['distName'] = getAreaName($item['dist']);
                $item['detailAddress'] = $item['provName'] . $item['cityName'] . $item['distName'] . $item['address'];
            }
            */

            /*
            if( strpos($fields,'*') !==false || (strpos($fields,'main_business')) !==false ) {
                //企业类别
                $types = str_replace('[', '', $item['main_business']);
                $types = str_replace(']', '', $types);
                $productService = Beans::get('product.productType.service');
                $items = $productService->getItems(array('id' => array('$in' => $types)), 'id,name', null);
                $temp = "";
                foreach ($items as $val) {
                    $temp .= $val['name'] . "   ";
                }
                $item['main_business_name'] = $temp;
            }
            */
            $resVo =  new AjaxResult(AjaxResult::OP_SUCCESS,"success",null);
            $resVo -> putItem($item);
            return $resVo;
        }else{
            return new AjaxResult(AjaxResult::OP_FAILURE,"user not found",null);
        }
    }

    /**
     * MPE会员对应的APPID获取大塑支付的用户信息
     * @param $appid
     * @param $fields string 需要获取的字段
     * @return AjaxResult
     */
    public function getUserByAppId( $appid, $fields="id" ){
        $condition['install_id'] = $appid;
        $model = Loader::model('appStatAccount');
        $item = $model -> getItem($condition,"userid",null);

        if( $item ){
            $service = Beans::get('user.user.service');
            $items = $service -> getItem(array("id"=>$item['userid']),$fields.',payway',null);
            $service = Beans::get('payment.payway.service');
            $payway = $service->getItem(array('id' => $items['payway']),'name',null);
            $items['sign_bank_name'] = $payway['name'];
            $resVo = new AjaxResult(AjaxResult::OP_SUCCESS,"success",null);
            $resVo -> putItem($items);
            return $resVo;
        }else{
            return new AjaxResult(AjaxResult::OP_FAILURE,"appid not found",null);
        }
    }

    /**
     * MPE会员对应的APPID获取大塑支付的UserId
     * @param $appid
     * @param $fields
     * @return AjaxResult
     */
    public function getCompanyByAppId( $appid, $fields="*" ){
        $condition['install_id'] = $appid;
        $model = Loader::model('appStatAccount');
        $item = $model -> getItem($condition,"userid",null);
        if( $item ){
            $companyService = Beans::get('user.company.service');
            $companyItem = $companyService -> getItem(array('userid'=>$item['userid']),$fields,null);
            if( $item ) {
                $retVo = new AjaxResult(AjaxResult::OP_SUCCESS, "success", null);
                $retVo -> putItem($companyItem);
                return $retVo;
            }
            else{
                return new AjaxResult(AjaxResult::OP_FAILURE,"user not found",null);
            }
        }else{
            return new AjaxResult(AjaxResult::OP_FAILURE,"appid not found",null);
        }
    }
}
